package controllers

import (
	"encoding/base64"
	"encoding/json"
	"github.com/astaxie/beego/logs"
	"smart_home/api/xfyun/afters"
	"smart_home/api/xfyun/depots"
	"sort"
	"strings"
	"tools"
)

type XfyunAfterController struct {
	BaseController
}

type xfyunSign struct {
	Signature string `json:"signature" form:"signature"`
	Timestamp string `json:"timestamp" form:"timestamp"`
	Rand      string `json:"rand" form:"rand"`
}

var xfTokens = make(map[string]string)

func init() {
	xfTokens["webapi"] = "f40d050594445ec5"
	xfTokens["android"] = "3b21348e26f1b028"
	xfTokens["custom"] = "3b21348e26f1b028"
}

// @Title Create
// @Description xfyun后处理
// @router /after/:platform [post]
func (c *XfyunAfterController) AfterPost() {
	var (
		res      *depots.Result
		resp     *depots.Response
		err      error
		dcode    []byte
		content  *depots.Content
		platform string
	)

	c.Ctx.Input.Bind(&platform, ":platform")

	res = &depots.Result{
		Answer: &depots.Answer{
			Type: depots.ANSWER_TEXT,
			Text: "你好，我还不懂你的意思",
		},
	}

	defer func(res *depots.Result, c *XfyunAfterController) {
		logs.Debug("Result: %+v\n", res.Answer)
		c.Data["json"] = res
		c.ServeJSON()
	}(res, c)

	resp = &depots.Response{}
	content = &depots.Content{}

	// 如果事自定义后处理
	if platform == "custom" {
		err = json.Unmarshal(c.Ctx.Input.RequestBody, &content.Intent)
		logs.Debug("content.Intent:%+v / error:%+v", content, err)
		goto Del
	}

	if err = json.Unmarshal(c.Ctx.Input.RequestBody, resp); err != nil {
		logs.Error("afterResponse Unmarshal error", err)
		return
	}

	logs.Debug("%s", c.Ctx.Input.RequestBody)

	if dcode, err = base64.StdEncoding.DecodeString(resp.Msg.Content); err != nil {
		logs.Error("encodeContent base64 decode error:", err)
		return
	}

	if err = json.Unmarshal(dcode, content); err != nil {
		logs.Debug("content Unmarshal error:", err)
		return
	}

Del:
	if len(content.Intent.Answer.Text) > 0 {
		res.Answer.Text = content.Intent.Answer.Text
	}

	logs.Debug("content.Intent.Data:%+v", content.Intent)
	if len(content.Intent.Semantic) > 0 {
		err = afters.RunAfter(content.Intent.Semantic[0].Intent, &content.Intent, res)
		if err != nil {
			logs.Debug("RunAfter error :", err)
		}
	}
}

// @Title Create
// @Description xfyun后处理
// @router /after/:platform [get]
func (c *XfyunAfterController) AfterValidate() {
	var (
		sign     *xfyunSign
		err      error
		platform string
		tk       string
		arr      []string
	)

	sign = &xfyunSign{}
	if err = c.ParseData(sign); err != nil {
		return
	}

	c.Ctx.Input.Bind(&platform, ":platform")
	tk, ok := xfTokens[platform]
	if !ok {
		return
	}

	arr = []string{
		tk,
		sign.Timestamp,
		sign.Rand,
	}

	sort.Strings(arr)
	str := strings.Join(arr, "")
	encode := tools.Sha1(str)
	if encode == sign.Signature {
		c.Ctx.ResponseWriter.Write([]byte(tools.Sha1(tk)))
		c.StopRun()
	}
}
